AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include('shared.lua')

ENT.WireDebugName = "Laser Sensor"

local MODEL = Model("models/jaanus/wiretool/wiretool_range.mdl")

function ENT:Initialize()
	self.Entity:SetModel( MODEL )
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )
	self.Entity:StartMotionController()

	self.Outputs = Wire_CreateOutputs(self.Entity, { "Out" })
end

function ENT:Setup( max_range, show_beam, ar, ag, ab, aa, br, bg, bb, ba, ignworld, ignprops )
	self.MaxRange = max_range
	self.ShowBeam = show_beam
	self.ColorOff = { ar, ag, ab, aa }
	self.ColorOn =  { br, bg, bb, ba }
	self.IgnoreWorld = ignworld
	self.IgnoreProps = ignprops
	
	if (show_beam) then
		self:SetBeamLength(math.min(self.MaxRange, 2000))
	else
		self:SetBeamLength(0)
	end
	
	self:TriggerOutput(0)
	self:ShowOutput()
end

function ENT:Output()
	return self.Value
end

function ENT:TriggerInput(iname, value)
	
end

function ENT:Think()
	self.BaseClass.Think(self)

	local trace = {}
	trace.start = self.Entity:GetPos()
	trace.endpos = trace.start + (self.Entity:GetUp() * self.MaxRange)
	trace.filter = { self.Entity }

	local trace = util.TraceLine(trace)
	
	if ( trace.Hit ) then
	    if (trace.Entity:IsValid()) then
		    if (trace.Entity:IsPlayer() or trace.Entity:IsNPC() or trace.Entity:IsVehicle()) then on = 1
			elseif (not self.IgnoreProps) then on = 1
			else on = 0 end
		elseif (not self.IgnoreWorld) then
		    on = 1
		else
		    on = 0
		end
	else
	    on = 0
	end
	
	if (on == 0) then self.Entity:SetColor(self.ColorOff[1], self.ColorOff[2], self.ColorOff[3], self.ColorOff[4])
	else              self.Entity:SetColor(self.ColorOn[1], self.ColorOn[2], self.ColorOn[3], self.ColorOn[4])
	end
	
	self:TriggerOutput(on)
	self:ShowOutput()
	
	self.Entity:NextThink(CurTime()+0.04)
	return true
end

function ENT:ShowOutput()
	local text = "Laser Sensor"
	if(self.Outputs["Out"])then
	   if(self.Outputs["Out"].Value>0)then
	       text = text .. "\nOut=1"
	   else
	       text = text.. "\nOut=0"
	   end
	end
	self:SetOverlayText( text )
end

function ENT:TriggerOutput(out)
    Wire_TriggerOutput(self.Entity, "Out", out)
end
